#include "TDBase.h"

PathRecyclePool::PathRecyclePool(void)
{
}

PathRecyclePool::~PathRecyclePool(void)
{
}

PathInfo PathRecyclePool::FindPath(const StageMap& map, int beginBrickIdx, int endBrickIdx)
{
	// any exist path meet condition ?
	for (int i=0; i<(int)_pool.size(); i++)
	{
		if (_pool[i].EndBrickIdx() == endBrickIdx)
		{
			int segIdx =_pool[i].GetSegIdxOf(beginBrickIdx);
			if (segIdx>=0)
			{
				_pool[i].Retain();
				return PathInfo(i, segIdx);
			}
		}
	}

	// get a free path object, and search the map to it
	int pathIdx = FindFreePath();
	bool find = _pathFinder.Find(map, beginBrickIdx, endBrickIdx, _pool[pathIdx]);
	
	if (find)
	{
		_pool[pathIdx].Retain();
		return  PathInfo(pathIdx, 0);
	}
	
	assert (false);
	return  PathInfo(-1, -1);
}

const MapPath& PathRecyclePool::At(int idx) const
{
	assert (idx>=0 && idx <(int)_pool.size());

	return _pool[idx];
}

int PathRecyclePool::FindFreePath()
{
	if (_freeList.empty())
	{
		_pool.push_back(MapPath());
		return _pool.size() -1;
	}

	int idx =_freeList.back();
	_freeList.pop_back();
	_pool[idx].Clear();

	return idx;
}

int PathRecyclePool::Size() const
{
	return _pool.size();
}

void PathRecyclePool::ReleasePath (int idx)
{
	assert (idx>=0 && idx <(int)_pool.size());
	assert (!_pool[idx].IsFree());
	
	_pool[idx].Release();
	if (_pool[idx].IsFree())
	{
		_freeList.push_back(idx);
	}

}